using System;
using System.Collections.Generic;
using System.Linq;
using FwkLight.CodeExtensions;

namespace FwkLight.Domain.Fetching
{
  public class EntityAliasParser : IEntityAliasParser
  {
    public string ParseAliasFor(object entity, IList<string> alisesToAvoid)
    {
      return ParseAliasFor(entity.GetType(), alisesToAvoid);
    }

    public string ParseAliasFor(Type entityType, IList<string> alisesToAvoid)
    {
      string alias = entityType.Name;
      alias.ForEach(p =>
      {
        if (char.IsLower(p))
          alias = alias.Replace(p, char.Parse(" "));
      });
      
      string initialResult = alias.Replace(" ", "").ToLower();
      if (alisesToAvoid != null)
      {
        string finalResult = initialResult;
        bool currentAliasIsUsed = alisesToAvoid.Any(p => p == finalResult);

        if (currentAliasIsUsed)
        {
          int idx = 0;
          while (currentAliasIsUsed)
          {
            idx++;
            finalResult = initialResult + idx;
            currentAliasIsUsed = alisesToAvoid.Any(p => p == finalResult);
          }
        }

        return finalResult;
      }

      return initialResult;
    }
  }
}